package com.redstar.HappyRefresh.service.impl;

import com.google.code.kaptcha.Producer;
import com.redstar.HappyRefresh.constant.RedisConstant;
import com.redstar.HappyRefresh.service.CaptchaService;
import com.redstar.HappyRefresh.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private Producer producer; // kaptcha框架
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public BufferedImage getCaptcha(String uuid) { // 通过kaptcha框架生成图片验证码
        try {
            // uuId在前端生成，后端生成图片验证码后与uuId绑定，需要设置过期时间
            String code = producer.createText();
            // 图片验证码储存在redis中，比写入数据库更合适
            redisTemplate.opsForValue().set(RedisConstant.PICTURE_CODE + uuid, code); // 图片验证码可以在登录验证时进行删除
            return producer.createImage(code);
        } catch (Exception e) {
            throw new RuntimeException("getCaptcha方法出错：" + e.getMessage());
        }
    }

    @Override
    public void emailCode(String email) { // 发送邮箱验证码
        // 随机生成6位验证码
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            str.append((int) (Math.random() * 10));
        }
        String code = str.toString();
        // 将邮箱验证码记录在redis中，有效期为5分钟
        redisTemplate.opsForValue().set(RedisConstant.EMAIL_CODE + email, code, RedisConstant.EMAIL_CODE_TIME);
        // 发送邮件
        emailService.send(email, "验证码为：" + code + "，验证码5分钟之内有效");
    }
}
